package com.software.car.common.utils;

import com.software.car.common.enums.ResultEnum;
import com.software.car.common.exception.MyException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;

/**
 * @Description
 * @Author 魔法はまだ解けない
 * @Date 2021/1/17
 */
public class JwtUtil {

    private final static Logger log = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * JWT 过期实际，时间为12小时
     */
    private static final int EXPIRE_TIME = 12 * 60 * 60 * 1000;

    /**
     * 密钥对象，以前token版本是通过签名校验
     */
    private static final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS512);

    /**
     * 构造token
     * @param id 用户id
     * @return
     */
    public static String generate(String id) {
        String token = Jwts.builder()
                //设置失效时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                //加入额外数据
                .setId(id)
                //设置密钥对象及加密算法
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
        return token;
    }
    /**
     * 构造token
     * @param map 数据对象
     * @return
     */
    public static String generate(HashMap<String,Object> map) {
        String token = Jwts.builder()
                //设置失效时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                //加入额外数据
                .setClaims(map)
                //设置密钥对象及加密算法
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
        return token;
    }

    /**
     * 校验token，拿出用户id
     * @param token
     * @return
     * @throws RuntimeException
     */
    public static String validate(String token) throws MyException {
        if (token == null || token.length() == 0) {
            //抛出异常
            throw new MyException(ResultEnum.TOKEN_LENGTH_EXCEPTION);
        }
        Jws<Claims> claimsJws = Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token);
        String id = claimsJws.getBody().getId();
        return id;
    }
    /**
     * 校验token，拿出用户id
     * @param token
     * @return
     * @throws RuntimeException
     */
    public static Object getMessage(String token,String name) throws MyException {
        if (token == null || token.length() == 0) {
            //抛出异常
            throw new MyException(ResultEnum.TOKEN_LENGTH_EXCEPTION);
        }
        Jws<Claims> claimsJws = Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token);
        String id = claimsJws.getBody().getId();

        return claimsJws.getBody().get(name);
    }
}
